package com.example.mylibrary.http;
import com.example.mylibrary.global.GlobalConfig;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpManager {
   // private static volatile HttpManager httpManager;
    private static volatile HttpManager httpManager;
//    public static HttpManager getInstance(){
//        if (httpManager==null){
//            synchronized (HttpManager.class){
//                if (httpManager==null){
//                    httpManager=new HttpManager();
//                }
//            }
//        }
//        return httpManager;
//    }

    public static HttpManager getInstance(){
        if(httpManager==null){
            synchronized (HttpManager.class){
                if (httpManager==null){
                    httpManager=new HttpManager();
                }
            }
        }
        return httpManager;
    }
//    private Retrofit getRetrofit(String baseUrl,long timeout,TimeUnit timeUnit){
//        return new Retrofit.Builder()
//                .baseUrl(baseUrl)
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .client(getOkhttpClient(timeout,timeUnit))
//                .build();
//    }
    private Retrofit getRetrofit(String baseUrl,long timeout,TimeUnit timeUnit){
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkhttpClient(timeout,timeUnit))
                .build();
    }

    //获取okhttp客户端
    public OkHttpClient getOkhttpClient(long timeout,TimeUnit timeUnit) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder .connectTimeout(timeout,timeUnit);
        builder.writeTimeout(timeout, timeUnit);
        builder .readTimeout(timeout, timeUnit);
        builder .retryOnConnectionFailure(true);

        if (GlobalConfig.getInstance().getInterceptors()!=null){
            for (Interceptor interceptor : GlobalConfig.getInstance().getInterceptors()) {
                builder.addInterceptor(interceptor);
            }
        }
        return builder.build();
    }

    public <T> T createServer(Class<T>mClass,String baseUrl,long timeout,TimeUnit timeUnit){
        return getRetrofit(baseUrl,timeout,timeUnit).create(mClass);
    }

}

